// Copyright 2013 The Go Circuit Project
// Use of this source code is governed by the license for
// The Go Circuit Project, found in the LICENSE file.
//
// Authors:
//   2013 Petar Maymounkov <p@gocircuit.org>

package focus

import (
	"circuit/kit/rh"
	"circuit/kit/rh/ns"
	"circuit/kit/rh/xy"
)

// loci is a namespace of type ns.MapDir listing all circuit loci.
type loci struct {
	peer    *Peer
	peers   PeerFunc
	shutter rh.FID // Non-cross
}

func newLoci(peer *Peer, peers PeerFunc, shutter rh.FID) *loci {
	return &loci{
		peer:    peer,
		peers:   peers,
		shutter: shutter,
	}
}

func (l *loci) Map() map[string]ns.Dir { // If Map panics, the panic will be reported as ErrIO to RH, and subsequently syscall.EIO to FUSE.
	bulk := l.peers()
	dir := make(map[string]ns.Dir)
	for _, peer := range bulk {
		//
		if peer.ID() == l.peer.ID() {
			dir[peer.Key()] = l.shutter
			continue
		}
		ysrv := xy.YServer{peer.Shutter}
		yssn, err := ysrv.SignIn("focus/"+l.peer.Key(), "/")
		if err != nil {
			continue
		}
		yfid, err := yssn.Walk(nil)
		if err != nil {
			continue
		}
		dir[peer.Key()] = yfid
	}
	return dir
}
